import { filterAsyncRouter } from "./../../utils/permission";
import { layoutMap } from "./../../router/router";
import { defineStore, StoreGeneric } from "pinia";
import { UserModel } from "@/model/userModel";
import { _RouteRecordBase } from "vue-router";
import { markRaw } from "vue";
import { tagsStore } from "../tagsStore";
// 将访问过的路由固定到visited views bar
function handleFixedVisitedViews(
  tagsViewStore: StoreGeneric,
  routes: _RouteRecordBase[],
) {
  routes.forEach((route) => {
    if (route.meta && route.meta.fixed) {
      tagsViewStore.handleAddFixedVisitedView(route);
    }
    if (route.children && route.children.length)
      handleFixedVisitedViews(tagsViewStore, route.children);
  });
}
export const userStore = defineStore("user", {
  state: (): {
    users: UserModel;
    routers: any[];
    currentRouteName: any[];
  } => ({
    users: {},
    routers: [],
    currentRouteName: [],
  }),
  getters: {
    getUserName: (state) => !!state.users && state.users.userName,
    getBreadName: (state) => state.currentRouteName,
  },
  actions: {
    clearUser() {
      this.users = {};
      this.routers = [];
    },
    setUser(user: UserModel) {
      console.log("user", user);

      const routers = markRaw(layoutMap);
      const accessedRouters = filterAsyncRouter(routers, user.permissions);
      this.users = user;
      this.routers = accessedRouters;
      handleFixedVisitedViews(tagsStore(), routers);
    },

    setBreadcrumb(arr: any[]) {
      const newBreadArr = arr?.filter((item) => {
        return item.meta && JSON.stringify(item.meta) != "{}";
      });
      const titles = newBreadArr?.map((item) => {
        return {
          title: item?.meta?.title,
          path: item?.path,
        };
      });

      this.currentRouteName = titles;
    },
  },
});
